/**
 * 
 */
package com.huyi.lock.zookeeperlock;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * 描述：	
 * @author shengli.hu
 * @since 1.8	
 * @version 1.0
 */
public class ZookeeperApi {

	static String hostPort = "10.194.80.121:2181";
	static String rootPath = "/zklock";

	public static void main(String[] args) {
		try {

			// 连接zk
			ZooKeeper zk = new ZooKeeper(hostPort, 3000, null);
			
			/**
			 *  创建节点
			 */
			// 1、创建永久节点
			Stat stat = zk.exists(rootPath, true);
			if(stat == null) {
				String persistentNode = zk.create(rootPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
				System.out.println("永久节点创建：" + persistentNode);
			}

			// 2、创建虚拟节点
			String viNode = zk.create(rootPath + "/test_lock", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
			System.out.println("虚拟节点创建：" + viNode);
			
			// 3、创建顺序虚拟节点
			String viNode1 = zk.create(rootPath + "/test_lock_", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
			System.out.println("虚拟顺序节点1创建：" + viNode1);
			String viNode2 = zk.create(rootPath + "/test_lock_", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
			System.out.println("虚拟顺序节点2创建：" + viNode2);
			
			/**
			 * 获取子节点
			 */
			List<String> nodes = zk.getChildren(rootPath, true);
			System.out.println("子节点列表：" + nodes);
/*			for(int i =0;i<nodes.size();i++) {
				System.out.println("子节点列表：" + nodes.get(i));
			}*/
			
			zk.exists(rootPath + "/test_lock_", new Watcher(){

				@Override
				public void process(WatchedEvent event) {
					System.out.println("已经触发了" + event.getType() + "事件！"); 
				}
				
			});
			
			 // 删除子目录节点
			zk.delete(rootPath + "/test_lock", -1); 
			
			System.in.read();
			
			zk.close();
		} catch (IOException | KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
